package com.liangtian.mdm.system.menu.service.impl;

import com.liangtian.mdm.dm.listener.CacheUtil;
import com.liangtian.mdm.dm.model.dao.ModelDao;
import com.liangtian.mdm.dm.model.model.Model;
import com.liangtian.mdm.system.menu.dao.MenuDao;
import com.liangtian.mdm.system.menu.model.Menu;
import com.liangtian.mdm.system.menu.model.MenuShow;
import com.liangtian.mdm.system.menu.service.MenuService;
import com.liangtian.mdm.system.business.dao.SysBusinessDao;
import com.liangtian.mdm.system.business.model.SysBusiness;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImp implements MenuService {

    //注入dao
    @Autowired
    MenuDao menuDao;

    @Autowired
    ModelDao modelDao;

    @Autowired
    SysBusinessDao sysBusinessDao;

    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public List<MenuShow> quertMenu() {

        List<MenuShow> menuShowLst = new ArrayList<MenuShow>();
//		List<MenuShow> secShowLst=new ArrayList<MenuShow>();
//		List<MenuShow> thirShowLst=new ArrayList<MenuShow>();

        Menu menu = new Menu();
        menu.setStatus("0");
        menu.setGrade("1");
        List<Menu> firstLst = menuDao.queryMenuByGrade(menu); //查询一级菜单
        for (Menu first : firstLst) {
            MenuShow menuS = new MenuShow();
            menuS.setMenu_id(first.getMenu_id());
            menuS.setName(first.getName());

            menu.setGrade("2");
            menu.setSuper_id(first.getMenu_id());//上级id
            List<Menu> secondLst = menuDao.queryMenuByGrade(menu);//查询二级菜单
            List<MenuShow> secShowLst = new ArrayList<MenuShow>();
            for (Menu second : secondLst) {
                MenuShow menuSecond = new MenuShow();
                menuSecond.setMenu_id(second.getMenu_id());
                menuSecond.setName(second.getName());
                menuSecond.setSuper_id(second.getSuper_id());
                secShowLst.add(menuSecond);
                menuS.setNextMenu(secShowLst);

                menu.setGrade("3");
                menu.setSuper_id(second.getMenu_id());//上级id
                List<Menu> thirdLst = menuDao.queryMenuByGrade(menu);//查询三级级菜单
                List<MenuShow> thirShowLst = new ArrayList<MenuShow>();
                for (Menu thied : thirdLst) {
                    MenuShow menuThir = new MenuShow();
                    menuThir.setMenu_id(thied.getMenu_id());
                    menuThir.setName(thied.getName());
                    menuThir.setSuper_id(thied.getSuper_id());
                    menuThir.setUrl(thied.getUrl());
                    thirShowLst.add(menuThir);
                    menuSecond.setNextMenu(thirShowLst);
                }
            }
            menuShowLst.add(menuS);
        }

//		menu.setGrade("2");
//		menu.setStatus("0");
//		List<Menu> secondLst=menuDao.queryMenuByGrade(menu);//查询二级菜单
//		
//		menu.setGrade("3");
//		menu.setStatus("0");
//		List<Menu> thirdLst=menuDao.queryMenuByGrade(menu);//查询三级级菜单

//		menuLst.add(firstLst);
//		menuLst.add(secondLst);
//		menuLst.add(thirdLst);

//		StringBuffer sb=new StringBuffer();
//		sb.append("[");  //开始
//		for(Menu oneMenu:firstLst){  //循环拼写第一级菜单
//			sb.append("{\r\n");
//			sb.append("menu_id:\'"+oneMenu.getMenu_id()+"\',\r\n");
//			sb.append("menu_name:\'"+oneMenu.getName()+"\',\r\n");
//			sb.append("showOrder:\'"+oneMenu.getOrder_num()+"\',\r\n");
//			menu.setGrade("2");
//			menu.setStatus("0");
//			menu.setSuper_id(oneMenu.getMenu_id());//上级id
//			List<Menu> secondLst=menuDao.queryMenuByGrade(menu); //根据一级菜单的id查询二级菜单
//			sb.append("secondMenu:[");
//			for(Menu twoMenu:secondLst){  //拼接第二级菜单
//				sb.append("{\r\n");
//				sb.append("menu_id:\'"+twoMenu.getMenu_id()+"\',\r\n");
//				sb.append("pid:\'"+twoMenu.getSuper_id()+"\',\r\n");
//				sb.append("menu_name:\'"+twoMenu.getName()+"\',\r\n");
//				sb.append("showOrder:\'"+twoMenu.getOrder_num()+"\',\r\n");
//				 
//				menu.setGrade("3");
//				menu.setStatus("0");
//				menu.setSuper_id(twoMenu.getMenu_id());//上级id
//				List<Menu> thirdLst=menuDao.queryMenuByGrade(menu); //根据二级菜单的id查询三级菜单
//				sb.append("thirdMenu:[");
//				for(int i=0;i<thirdLst.size();i++){  //拼接第二级菜单
//					sb.append("{\r\n");
//					sb.append("menu_id:\'"+thirdLst.get(i).getMenu_id()+"\',\r\n");
//					sb.append("pid:\'"+thirdLst.get(i).getSuper_id()+"\',\r\n");
//					sb.append("menu_name:\'"+thirdLst.get(i).getName()+"\',\r\n");
//					sb.append("showOrder:\'"+thirdLst.get(i).getOrder_num()+"\',\r\n");
//					sb.append("url:\'"+thirdLst.get(i).getUrl()+"\'\r\n");
//					if(i==thirdLst.size()-1){
//						sb.append("}");
//					}else{
//						sb.append("},\r\n");
//					}
//				}
//				sb.append("]\r\n");  //第三级结束
//				sb.append("}\r\n");  //第二级菜单结束
//			}
//			sb.append("]\r\n");  //第二级菜单结束
//			sb.append("}");//第一级菜单结束
//		}
//		sb.append("];\r\n");  //结束
        return menuShowLst;
    }

    /**
     * 2016-10-09 honye 组装三级菜单
     */
    @Override
    public List<MenuShow> queryMenuShow() {
        Menu menu = new Menu();
        menu.setStatus("0");
        menu.setGrade("1");
        List<MenuShow> firstLst = menuDao.queryMenuShowByGrade(menu); //查询一级菜单
        //System.out.println(JSON.toJSONString(firstLst));

        for (MenuShow first : firstLst) {
            menu.setGrade("2");
            menu.setSuper_id(first.getMenu_id());//上级id
            List<MenuShow> secondLst = menuDao.queryMenuShowByGrade(menu);//查询二级菜单
            first.setNextMenu(secondLst);

            for (MenuShow second : secondLst) {
                menu.setGrade("3");
                menu.setSuper_id(second.getMenu_id());//上级id
                List<MenuShow> thirdLst = menuDao.queryMenuShowByGrade(menu);//查询三级级菜单
                second.setNextMenu(thirdLst);
            }
        }
        return firstLst;
    }

    @Override
    public void createMenu(String tableName) {
        String modelId = tableName.substring(tableName.indexOf("_") + 1, tableName.length());
        Model model = cacheUtil.getModel(modelId);
        SysBusiness sysBusinessCond = sysBusinessDao.selectBusByTable(tableName);
        if (sysBusinessCond != null) {
            if (model.getIsMenuCreate() == 1) {//判断菜单是否创建啦
                menuDao.deleteMenuByModelId(modelId);
            }
            //更新业务类型
            updateSysBusness(sysBusinessCond, model);
        } else {
            //插入业务类型模块//创建一个sysBusiness对象
            SysBusiness sysBusiness = new SysBusiness();
            if (model.getIsSubtable() == 1) {//说明是从表
                if ("0".endsWith(model.getModelType())) {//说明这是主数据
                    sysBusiness.setIsRadio("1");
                    sysBusiness.setIsWorkflow("0");
                } else {//说明是字典
                    sysBusiness.setIsRadio("1");
                    sysBusiness.setIsWorkflow("0");
                }
            } else {//说明是主表
                if ("0".endsWith(model.getModelType())) {//说明这是主数据
                    sysBusiness.setIsRadio("1");
                    sysBusiness.setIsWorkflow(model.getIsWorkflow() + "");
                } else {//说明是字典
                    sysBusiness.setIsRadio("1");
                    sysBusiness.setIsWorkflow("0");
                }
            }

            sysBusiness.setBusName(model.getModelName());
            sysBusiness.setBusType(model.getModelType());
            sysBusiness.setBusTable(model.getTableName());
            sysBusiness.setBusTableName(model.getModelName());

            sysBusiness.setIsUsed("1");
            //这一块是个问题，需要解决，如何动态的生成父类是主数据的业务类型
            sysBusiness.setPid("1262");//主数据插入到一个固定的值
            sysBusinessDao.insertBusiness(sysBusiness);//插入到业务类型表
        }
        //菜单创建--只有主表生成菜单，从表不生成菜单
        if (model.getIsSubtable() != 1) {
            Menu menu = new Menu();
            //0 基本主数据 1 字典 2 树形主数据 3 树形字典
            menu.setName(model.getModelName()); //二级菜单的名字
            menu.setGrade("2");
            menu.setShow_name(model.getModelName());
            menu.setStatus("0");
            if ("1".equals(model.getModelType())) { //字典表放到字典菜单下面
                menu.setSuper_id("4");//默认字典类型的id为4
            } else {
                menu.setSuper_id("1");//默认主数据类型的id为1
            }
            menu.setModel_id(modelId);//菜单所属的模型id
            String orderNum = menuDao.queryMaxOrderByGrade("2");
            if (null == orderNum) {
                menu.setOrder_num("1");
            } else {
                menu.setOrder_num((Integer.valueOf(orderNum) + 1) + "");
            }
            String secMenuId = menuDao.queryMenuId();
            menu.setMenu_id(secMenuId);
            menuDao.insertMenu(menu);  //将二级菜单插入，返回id
            List<String> pageNames = this.getPageNamesByModelType(model.getModelType());
            for (int i = 0; i < pageNames.size(); i++) { //主数据类型生成四个菜单，三级菜单
                String menuId = menuDao.queryMenuId();
                menu.setMenu_id(menuId);
                menu.setName(model.getModelName() + pageNames.get(i)); //三级菜单的名字
                menu.setGrade("3");
                menu.setShow_name(model.getModelName() + pageNames.get(i));
                menu.setStatus("0");
                menu.setSuper_id(secMenuId);//刚插入的二级菜单的id
                menu.setOrder_num((i + 1) + "");
                menu.setMenu_type(this.formatMenuType(pageNames.get(i)));
                String urlName = this.formatName(pageNames.get(i), model.getClassType(), model.getModelType());
                if ("0".equals(model.getClassType())) {//如果是列表
                    menu.setUrl("/am/" + model.getTableName() + "/" + model.getTableName() + "_" + urlName + ".jsp");
                } else if ("1".equals(model.getClassType())) {//如果是父子树
                    menu.setUrl("/am/" + model.getTableName() + "/" + model.getTableName() + "_treeTabMain.jsp?menu_url=" + "/am/" + model.getTableName() + "/" + model.getTableName() + "_" + urlName + ".jsp");
                } else if ("2".equals(model.getClassType())) {//分类树
                    menu.setUrl("/am/" + model.getTableName() + "/" + model.getTableName() + "_treeTabMain.jsp?menu_url=" + "/am/" + model.getTableName() + "/" + model.getTableName() + "_" + urlName + ".jsp");
                }
                menuDao.insertMenu(menu);  //返回id
            }
            if ("0".equals(model.getClassType())) {
                menu.setMenu_id(menuDao.queryMenuId());
                menu.setName(model.getModelName() + "分发日志查询");
                menu.setSuper_id("6");
                menu.setShow_name(model.getModelName() + "分发日志查询");
                menu.setStatus("0");
                menu.setGrade("2");
                menu.setOrder_num(model.getId());
                menu.setMenu_type("list");
                menu.setMenu_id(modelId);
                menu.setUrl("/am/" + model.getTableName() + "/" + model.getTableName() + "_disList" + ".jsp");
                menuDao.insertMenu(menu);  //返回id
            }
        }
        //更改模型主表
        if (model.getIsSubtable() == 1) {//说明是从表
            model.setIsWorkflow(0);
        }
        model.setIsMenuCreate(1);
        modelDao.updateModelFlag(model);  //修改模型菜单已经创建
        //查询从表
        List<Model> subModels = modelDao.isHasSub(modelId);
        if (!subModels.isEmpty()) {
            for (Model sub : subModels) {
                createMenu(sub.getTableName());
            }
        }
    }

    //根据业务类型和模型，去更新业务类型数据
    public void updateSysBusness(SysBusiness sysBus, Model model) {
        if (model.getIsSubtable() == 1) {//说明是从表
            if ("0".endsWith(model.getModelType())) {//说明这是主数据
                sysBus.setIsRadio("1");
                sysBus.setIsWorkflow("0");
            } else {//说明是字典
                sysBus.setIsRadio("1");
                sysBus.setIsWorkflow("0");
            }
        } else {//说明是主表
            if ("0".endsWith(model.getModelType())) {//说明这是主数据
                sysBus.setIsRadio("1");
                sysBus.setIsWorkflow(model.getIsWorkflow() + "");
            } else {//说明是字典
                sysBus.setIsRadio("1");
                sysBus.setIsWorkflow("0");
            }
        }
        sysBus.setBusName(model.getModelName());
        sysBus.setBusType(model.getModelType());
        sysBusinessDao.updateBus(sysBus);
    }

    private List<String> getPageNamesByModelType(String type) {
        List<String> pageNames = new ArrayList<String>();
        if ("2".equals(type) || "0".equals(type)) {
            pageNames.add("查询");
            pageNames.add("申请");
            pageNames.add("审核");
            pageNames.add("修改");
        } else {
            pageNames.add("查询");
            pageNames.add("申请");
            pageNames.add("维护");
        }
        return pageNames;
    }

    private String formatName(String pageName, String classType, String modelType) {
        String urlName = "";
        if ("0".equals(modelType) && "0".equals(classType)) {  //基本主数据 列表
            if ("申请".equals(pageName)) {
                urlName = "apply";
            } else if ("查询".equals(pageName)) {
                urlName = "list";
            } else if ("审核".equals(pageName)) {
                urlName = "approve";
            } else {
                urlName = "update";
            }
        } else if ("1".equals(modelType) && "0".equals(classType)) {  //基本字典表 列表
            if ("申请".equals(pageName)) {
                urlName = "apply";
            } else if ("查询".equals(pageName)) {
                urlName = "zdList";
            } else {
                urlName = "wh";
            }
        } else if ("1".equals(modelType) && "2".equals(classType)) {  //基本字典表 分类树
            if ("申请".equals(pageName)) {
                urlName = "treeTabApply";
            } else if ("查询".equals(pageName)) {
                urlName = "treeTabZdList";
            } else {
                urlName = "treeTabWh";
            }
        } else if ("0".equals(modelType) && "1".equals(classType)) { //树形主数据  父子树
            if ("申请".equals(pageName)) {
                urlName = "treeTabApply";
            } else if ("查询".equals(pageName)) {
                urlName = "treeTabList";
            } else if ("审核".equals(pageName)) {
                urlName = "treeTabApprove";
            } else {
                urlName = "treeTabUpdate";
            }
        } else if ("0".equals(modelType) && "2".equals(classType)) { //树形主数据  分类树
            if ("申请".equals(pageName)) {
                urlName = "treeTabApply";
            } else if ("查询".equals(pageName)) {
                urlName = "treeTabList";
            } else if ("审核".equals(pageName)) {
                urlName = "treeTabApprove";
            } else {
                urlName = "treeTabUpdate";
            }
        } else {  //树形字典表
            if ("申请".equals(pageName)) {
                urlName = "treeTabApply";
            } else if ("查询".equals(pageName)) {
                urlName = "treeTabZdList";
            } else {
                urlName = "treeTabWh";
            }
        }

        return urlName;
    }

    private String formatMenuType(String pageName) {
        String menuType = "";
        if ("申请".equals(pageName)) {
            menuType = "apply";
        } else if ("查询".equals(pageName)) {
            menuType = "list";
        } else if ("审核".equals(pageName)) {
            menuType = "approve";
        } else if ("修改".equals(pageName)) {
            menuType = "update";
        } else {
            menuType = "wh";
        }
        return menuType;
    }

    @Override
    public List<Menu> menuTree(Menu menu) {
        return menuDao.queryMenuTree(menu);
    }

    @Override
    public PageInfo queryMenuByContion(Menu menu) {
        PageInfo<List<Menu>> pageInfo = null;
        try {
            Object pNo = menu.getPageNum();
            int pageNum, pageSize;
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(menu.getLimit());// 模型定义页面要显示数据条数
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<Menu> menuList = menuDao.queryMenuByContion(menu);
            pageInfo = new PageInfo(menuList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    @Override
    public void insertMenuForm(Menu menu) {
        menuDao.insertMenuForm(menu); //前台插入菜单

    }

    @Override
    public void updateMenuStatus(Menu menu) {
        menuDao.updateMenuStatus(menu);
    }

    @Override
    public Menu queryMenuById(Menu menu) {
        return menuDao.queryMenuById(menu);
    }

    @Override
    public void updateMenu(Menu menu) {
        menuDao.updateMenu(menu);
    }

    @Override
    public Menu queryOne(String MenuId) {
        return menuDao.queryOne(MenuId);
    }

    @Override
    public Menu queryThirMenu(Map<String, Object> param) {
        return menuDao.queryThirMenu(param);
    }

    @Override
    public Menu queryMenuUrlByModelId(Map<String, Object> param) {
        Menu menu = menuDao.queryMenuUrlByModelId(param);
        return menu;
    }

    /**
     * 2017-02-06 liyang 根据用户角色获取菜单权限
     */
    @Override
    public List<MenuShow> queryMenuShowByPermission(Map<String, Object> param) {
//		param.put("status", "0");
//		param.put("grade", "1");
//		List<MenuShow> firstLst = menuDao.queryMenuShowByPermission(param); //查询一级菜单
//		for(MenuShow first : firstLst){
//			param.put("grade", "2");
//			param.put("super_id", first.getMenu_id());//上级id
//			List<MenuShow> secondLst = menuDao.queryMenuShowByPermission(param);//查询二级菜单
//			first.setNextMenu(secondLst);
//			
//			for(MenuShow second:secondLst){
//				param.put("grade", "3");
//				param.put("super_id", second.getMenu_id());
//				List<MenuShow> thirdLst=menuDao.queryMenuShowByPermission(param);//查询三级级菜单
//				second.setNextMenu(thirdLst);
//			}
//		}
//		return firstLst;
        return menuDao.queryMenuShowByPermission(param);
    }

    @Override
    public Menu queryMenuByModelIdMenuType(Menu menu) {
        System.out.println("====" + menu.getMenu_id());
        return menuDao.queryMenuByModelIdMenuType(menu);
    }
}
